var express = require('express');
var router = express.Router();

var User = require('./../model/user');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

/**
* login
* 以及路由是 users 这里路径就不写 users 了
*/
router.post('/login', function(req, res, next) {
    var param = {
        userName: req.body.userName,
        userPwd: req.body.userPwd
    };
    // 通过 mongoose 查找修改数据库
    User.findOne(param, (err, doc) => {
        if(err){
            res.json({
                status: "1",
                msg: err.message
            });
        }else{
            // 接口调用成功
            if(doc){
                // 保存到 cookie
                res.cookie("userId", doc.userId, {
                    path: '/',
                    maxAge: 1000*60*60
                });
                res.cookie("userName", doc.userName, {
                    path: '/',
                    maxAge: 1000*60*60
                });
                // 保存 session，先要安装 express-session插件
                // req.session.user = doc;
                res.json({
                    status: "0",
                    msg: "",
                    result: {
                        userName: doc.userName
                    }
                });
            }
        }
    });
});

/**
* loginOut
*/
router.post('/loginOut', function(req, res, next) {
    // 清空服务器 cookie
    res.cookie("userId", "", {
        path: '/',
        maxAge: -1
    });
    res.json({
        status: "0",
        msg: "",
        result: ""
    });
});

/**
* checkLogin
* 判断是否登录，后台 cookie 或者 session 去控制的是否登录
*/
router.get('/checkLogin', function(req, res, next) {
    if(req.cookies.userId){
        // 如果id存在，也就是登录了，这样就返回 userName
        res.json({
            status: '0',
            msg: '',
            result: req.cookies.userName
        });
    }else{
        res.json({
            status: '1',
            msg: '未登录',
            result: ''
        });
    }
});

/**
* cartList Num
*/
router.get('/getCartCount', function(req, res, next) {
    if(req.cookies.userId){
        var userId = req.cookies.userId;
        User.findOne({userId: userId}, (err, doc) => {
            if(err){
                res.json({
                    status: "1",
                    msg: err.message,
                    result: ''
                });
            }else{
                if(doc){
                    var cartlist = doc.cartlist;
                    let cartCount = 0;
                    cartlist.map((item) => {
                        cartCount += parseInt(item.productNum);
                    });
                    res.json({
                        status: "0",
                        msg: '',
                        result: cartCount
                    });
                }
            }
        });
    }else{
        res.json({
            status: '1',
            msg: '未登录',
            result: ''
        });
    }
});

/**
* cartList
*/
router.get('/cartList', function(req, res, next) {
    var userId = req.cookies.userId;
    User.findOne({userId: userId}, (err, doc) => {
        if(err){
            res.json({
                status: "1",
                msg: err.message,
                result: ''
            });
        }else{
            if(doc){
                res.json({
                    status: "0",
                    msg: '',
                    result: doc.cartlist
                });
            }
        }
    });
});

/**
* 购物车删除
*/
router.post('/cart/del', function(req, res, next) {
    var userId = req.cookies.userId,
        productId = req.body.productId;
    User.update({
        userId: userId
    },{
        $pull:{
            'cartlist': {
                'productId': productId
            }
        }
    }, (err, doc) => {
        if(err){
            res.json({
                status: "1",
                msg: err.message,
                result: ''
            });
        }else{
            res.json({
                status: "0",
                msg: '',
                result: 'suc'
            });
        }
    });
});

/**
* 购物车数量修改
*/
router.post('/cart/edit', function(req, res, next) {
    var userId = req.cookies.userId,
        productId = req.body.productId,
        productNum = req.body.productNum,
        checked = req.body.checked;
    User.update({
        'userId': userId,
        'cartlist.productId': productId
    },{
        'cartlist.$.productNum': productNum,
        'cartlist.$.checked': checked
    },{
        multi:true
    }, (err, doc) => {
        if(err){
            res.json({
                status: "1",
                msg: err.message,
                result: ''
            });
        }else{
            res.json({
                status: "0",
                msg: '',
                result: doc
            });
        }
    });
});

/**
* 购物车全选状态
*/
router.post('/cart/checkAll', function(req, res, next) {
    var userId = req.cookies.userId,
        checkedAll = req.body.checkedAll;
    User.findOne({userId: userId}, (err, user) => {
        if(err){
            res.json({
                status: "1",
                msg: err.message,
                result: ''
            });
        }else{
            if(user){
                user.cartlist.forEach((item) => {
                    item.checked = checkedAll;
                });
                user.save((err1, doc) => {
                    if(err1){
                        res.json({
                            status: "1",
                            msg: err1.message,
                            result: ''
                        });
                    }else{
                        res.json({
                            status: "0",
                            msg: '',
                            result: 'suc'
                        });
                    }
                });
            }

        }
    });
});

/**
* addressList
*/
router.get('/addressList', function(req, res, next) {
    var userId = req.cookies.userId;
    User.findOne({userId: userId}, (err, doc) => {
        if(err){
            res.json({
                status: "1",
                msg: err.message,
                result: ''
            });
        }else{
            if(doc){
                res.json({
                    status: "0",
                    msg: '',
                    result: doc.addressList
                });
            }
        }
    });
});

/**
* 设置默认地址
*/
router.post('/setDefault', function(req, res, next) {
    var userId = req.cookies.userId,
        addressId = req.body.addressId;
    if(!addressId){
        res.json({
            status: "1003",
            msg: "Empty AddressId",
            result: ''
        });
    }else{
        User.findOne({userId: userId}, (err, doc) => {
            if(err){
                res.json({
                    status: "1",
                    msg: err.message,
                    result: ''
                });
            }else{
                var addressList = doc.addressList;
                addressList.forEach((item) => {
                    if(item.addressId == addressId){
                        item.isDefault = true;
                    }else{
                        item.isDefault = false;
                    }
                });
                // 保存数据
                doc.save((err1, doc1) => {
                    if(err1){
                        res.json({
                            status: "1",
                            msg: err1.message,
                            result: ''
                        });
                    }else{
                        res.json({
                            status: "0",
                            msg: '',
                            result: ''
                        });
                    }
                });
            }
        });
    }
});

/**
* addNewAddress
*/
router.post('/addNewAddress', (req, res, next) => {
    var userId = req.cookies.userId,
        addressName = req.body.addressName,
        tel = parseInt(req.body.tel),
        streetName = req.body.streetName,
        postCode = req.body.postCode;

    User.findOne({userId: userId}, (err, doc) => {
        if(err){
            res.json({
                status: "1",
                msg: err.message,
                result: ''
            });
        }else{
            if(doc){
                var addressList = doc.addressList,
                    num = parseInt(addressList.length) - 1,
                    addressId = addressList[num].addressId,
                    addressNewId = '';
                addressNewId = parseInt(addressId) + 1;
                var jsonNew = {
                    addressId: addressNewId,
                    addressName: addressName,
                    tel: tel,
                    streetName: streetName,
                    postCode: postCode
                };
                addressList.push(jsonNew);
                doc.save((err1, doc1) => {
                    if(err1){
                        res.json({
                            status: "1",
                            msg: err1.message,
                            result: ''
                        });
                    }else{
                        res.json({
                            status: "0",
                            msg: '',
                            result: 'suc'
                        });
                    }
                });
                
            }
        }
    });
});

/**
* editAddress
*/
router.post('/editAddress', (req, res, next) => {
    var userId = req.cookies.userId,
        addressId = req.body.addressId,
        addressName = req.body.addressName,
        tel = parseInt(req.body.tel),
        streetName = req.body.streetName,
        postCode = req.body.postCode;

    User.update({
        "userId": userId,
        "addressList.addressId": addressId
    },{
        'addressList.$.addressName': addressName,
        'addressList.$.tel': tel,
        'addressList.$.streetName': streetName,
        'addressList.$.postCode': postCode
    }, (err, doc) => {
        if(err){
            res.json({
                status: "1",
                msg: err.message,
                result: ''
            });
        }else{
            res.json({
                status: "0",
                msg: '',
                result: 'suc'
            });
        }
    });
});

/**
* 删除地址
*/
router.post('/deletAddress', function(req, res, next) {
    var userId = req.cookies.userId,
        addressId = req.body.addressId;
    if(!addressId){
        res.json({
            status: "1003",
            msg: "Empty AddressId",
            result: ''
        });
    }else{
        User.update({
            userId: userId
        },{
            $pull:{
                'addressList': {
                    'addressId': addressId
                }
            }
        }, (err, doc) => {
            if(err){
                res.json({
                    status: "1",
                    msg: err.message,
                    result: ''
                });
            }else{
                res.json({
                    status: "0",
                    msg: '',
                    result: 'suc'
                });
            }
        });
    }
});

module.exports = router;
